package com.cn.bukeManage.service.serviceImpl;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;

import org.apache.commons.lang.math.NumberUtils;
import org.apache.shiro.SecurityUtils;
import org.springframework.stereotype.Service;
import org.springframework.ui.Model;

import com.cn.bukeManage.consts.Consts;
import com.cn.bukeManage.dao.IndentDao;
import com.cn.bukeManage.dao.OrdersDao;
import com.cn.bukeManage.dao.UserDao;
import com.cn.bukeManage.pojo.Customer;
import com.cn.bukeManage.pojo.Customer_address;
import com.cn.bukeManage.pojo.Dealer;
import com.cn.bukeManage.pojo.Goods;
import com.cn.bukeManage.pojo.Indent;
import com.cn.bukeManage.pojo.Orders;
import com.cn.bukeManage.pojo.Sample;
import com.cn.bukeManage.pojo.User;
import com.cn.bukeManage.pojo.page.GoodsPage;
import com.cn.bukeManage.pojo.page.Goods_afterSalesPage;
import com.cn.bukeManage.pojo.page.IndentPage;
import com.cn.bukeManage.pojo.page.OrdersPage;
import com.cn.bukeManage.pojo.page.Page;
import com.cn.bukeManage.service.IndentService;
import com.cn.bukeManage.service.OrdersService;
import com.cn.bukeManage.service.SampleService;
import com.cn.bukeManage.utils.LuKeBeanUtil;
@Service("ordersService")
public class OrdersServiceImpl implements OrdersService {
	@Resource
	private OrdersDao ordersDao;
	@Resource
	private IndentService indentService;
	@Resource
	private SampleService sampleService;
	@Resource
	private IndentDao indentDao;
	@Resource
	private UserDao userDao;
	
	@Override
	public List<Map<String,Object>> showIndents(Integer currentPage,Integer status,Model model) {
		// TODO Auto-generated method stub
		Map<String, Object> map = new HashMap<>();
		Page page=new Page.PageBuilder().currentPage(currentPage).builder();
		map.put("userId", SecurityUtils.getSubject().getSession().getAttribute("userId"));
		map.put("status", status);
		page.setRows(indentDao.selectAllIndents(map)==null?0:indentDao.selectAllIndents(map).size());
		model.addAttribute("page",page);
		map.put("begin", (currentPage-1)*page.getPageSize());
		map.put("pageSize", page.getPageSize());
		List<Map<String ,Object>>list=indentDao.selectAllIndents(map);
		for(Map<String,Object> indentsMap : list){
			//得到订单下说有商品
			Double indentMyProfit=0.0;
			Double indentGoodsPrice=0.0;
			List<Map<String, Object>> goods=indentDao.selectGoodsOfMine((Integer)(indentsMap.get("indentId")));
			for(Map<String,Object> goodMap : goods){
				Double myRate=getMyProfitRateOfGoods(goodMap);
				indentMyProfit+=myRate*(Double.valueOf(String.valueOf(goodMap.get("goodsPrice"))));
				indentGoodsPrice+=Double.valueOf(String.valueOf(goodMap.get("goodsPrice")));
			}
			if(status==3 | status==8 |status==14 | status==15){
				indentsMap.put("indentMyProfit", indentMyProfit);
			}
			indentsMap.put("indentGoodsPrice", indentGoodsPrice);
		}
		return list;
	}
	
	/**
	 *  当前登录账号指定商品的利润率；
	 * @param goodsMap
	 * @return
	 */
	public Double getMyProfitRateOfGoods(Map<String,Object> goodsMap){
		Double myRate=0.00;
		//当前登录代理账号
		User user=userDao.getUserById(Integer.parseInt(String.valueOf(SecurityUtils.getSubject().getSession().getAttribute("userId"))));
		if(user!=null){
			switch (user.getVertification()) {
			case "1":
				myRate=Double.valueOf(String.valueOf(goodsMap.get("profitRateAgent")));  //代理商
				break;
			case "2":
				myRate=Double.valueOf(String.valueOf(goodsMap.get("profitRateDeclar")));	//经销商
				break;
			case "3":
				myRate=Double.valueOf(String.valueOf(goodsMap.get("profitRatePromotor")));//推广大使	
				break;
			default:
				break;
			}
		}
		return myRate;
	}
	
	
	
	
	/**
	 * 功能：各级代理指定商品的理论利润率 
	 * @param sampleId
	 * @return
	 */
//	public Map<String,Double>getProfitRateOfAgents(Integer sampleId){
//		Map<String,Double>map=new HashMap<>();
//		if(null==sampleId){
//			return map;
//		}
//		Sample sample=sampleService.getSampleById(sampleId);
//		if(sample !=null){
//			map.put("agent", sample.getFirstProfit());
//			map.put("declar", sample.getFSProfit());
//			map.put("promoter", sample.getSecondProfit());
//		}
//		return map;
//	}
	
	
	
	/**
	 * 功能：指定商品的我的实际利润率
	 * @param customerPhone
	 * @param sampleId
	 * @return
	 */
//	public Double getMySampleProfitRate(String customerPhone,Integer sampleId){
//		Double myProfitRate=0.0;
//		//推荐客户的用户ID
//		if(customerPhone==null | "".equals(customerPhone))
//			return myProfitRate;
//		//推荐客户下单的代理账号Id；
//		Integer usreId=userDao.getUserIdByCustomerPhone(customerPhone);
//		//当前登录代理账号
//		User user=userDao.getUserById(Integer.parseInt(String.valueOf(SecurityUtils.getSubject().getSession().getAttribute("userId"))));
//		if(user !=null && usreId !=null){
//			//查询该商品各级代理的利润率
//			Map<String,Double> profitsRateMap=getProfitRateOfAgents(sampleId);
//			switch (user.getVertification()) {
//			case "0"://我是代理商
//				if(user.getUserId()==usreId){
//					myProfitRate=profitsRateMap.get("agent")+profitsRateMap.get("declar")+profitsRateMap.get("promoter");
//				}
//				myProfitRate=profitsRateMap.get("agent");
//				break;
//		   case "1"://我是经销商
//				if(user.getUserId()==usreId){
//					myProfitRate=profitsRateMap.get("declar")+profitsRateMap.get("promoter");
//				}
//				myProfitRate=profitsRateMap.get("declar");
//				break;
//		   case "2": //我是推广大使
//				myProfitRate=profitsRateMap.get("promoter");
//				break;
//			default:
//				break;
//			}
//		}
//		return myProfitRate;
//	}
	
	
	/**
	 * 功能：指定商品的我的实际利润
	 * @param customerPhone
	 * @param goodsPrice
	 * @param sampleId
	 * @return
	 */
//	public  Map<String,Object>getMySampleProfit(String customerPhone,Double goodsPrice,Integer sampleId){
//		 Map<String,Object> map=new HashMap<>();
//		 if(customerPhone.isEmpty())return map;
//		 if(goodsPrice.isNaN())return map;
//		 if(sampleId==null)return map;
//		 Double myProfitRateOfSpecialedSample=getMySampleProfitRate(customerPhone,sampleId);
//		map.put("myProfitRateOfSpecialedSample", myProfitRateOfSpecialedSample);
//		map.put("myProfitOfSpecialedSample", myProfitRateOfSpecialedSample*goodsPrice);
//		return map;
//	}
	
	
	//得到顾客的新订单
//	public List<Map<String, Object>> getAllOrderByStatus(Model model, Integer currentPage,Integer status) {
//		OrdersPage page=new OrdersPage();
//		page.setCurrentPage(currentPage);
//		page.setStatus(status);
//		List<Orders> orders=ordersDao.getAllOrderByStatus(page);
//		Integer rows=ordersDao.getRowsOfAllOrderByStatus(page);
//		page.setRows(rows);
//		model.addAttribute("page",page);
//		List<Map<String,Object>> list=new ArrayList<>();
//		for(Orders orders2:orders){
//			Map<String,Object> map=new HashMap<>();
//			//订单id ,下单人, 收货人,下单时间,交货时间,备注,订单状态, 订单价格
//			map.put("orderId",orders2.getOrderId());
//			Customer customer=ordersDao.getCustomerByCustomerId(orders2.getCustomerId());
//			map.put("nickName",customer.getNickName());
//			SimpleDateFormat simpleDateFormat=new SimpleDateFormat("YYYY/MM/dd HH:MM:SS");
//			if (orders2.getDeliveryTime()==null) {
//				map.put("deliverTime","");			
//			}
//			map.put("beginTime",simpleDateFormat.format(orders2.getBeginTime()));
//			map.put("remark",orders2.getRemark());
//			map.put("status",orders2.getStatus());
//			//收货人
//			Customer_address customer_address= ordersDao.getAddressByCuAdId(orders2.getCuAdId());
//			map.put("ShouHuoName",customer_address.getName());
//			map.put("orderPrice",orders2.getOrderPrice());
//			map.put("customerPrice",orders2.getCustomerPrice());
//			list.add(map);
//		}
//		return list;
//	}
	//顾客中各个订单的种类
//	public List<Map<String, Object>> getAllOrdersByStatus(Model model,Integer currentPage, Integer status,Integer afterSale) {
//		//List<Map<String,Object>> list=new ArrayList<>();
//		//这是顾客订单
//		OrdersPage page=new OrdersPage();
//		page.setCurrentPage(currentPage);
//		page.setStatus(status);
//		page.setAfterSale(afterSale);
//		//List<Orders> orders=ordersDao.getAllOrderByStatus(page);
//		List<Map<String, Object>>list=ordersDao.showIndents(currentPage);
//		return list;
//	}
	//根据不同的订单得到页码, 分页详情
	public OrdersPage getPageOfOrders(Integer currentPage,Integer status,Integer afterSale) {
		OrdersPage ordersPage=new OrdersPage();
		ordersPage.setCurrentPage(currentPage);
		ordersPage.setStatus(status);
		ordersPage.setAfterSale(afterSale);
		Integer rows = ordersDao.getRowsOfAllOrderByStatus(ordersPage);
		ordersPage.setRows(rows);
		return ordersPage;
	}
	//处理中得到所有处理中顾客的订单
	public List<Map<String, Object>> getAllGoingOrder(Model model, Integer currentPage) {
		OrdersPage page=new OrdersPage();
		page.setCurrentPage(currentPage);
		List<Orders> orders=ordersDao.getAllGoingOrder(page);
		Integer rows=ordersDao.getRowsOfAllGoingOrder(page);
		page.setRows(rows);
		model.addAttribute("page",page);
		List<Map<String,Object>> list=new ArrayList<>();
		for(Orders orders2:orders){
			Map<String,Object> map=new HashMap<>();
			//订单id ,下单人, 收货人,下单时间,交货时间,备注,订单状态, 订单价格
			map.put("orderId",orders2.getOrderId());
			Customer customer=ordersDao.getCustomerByCustomerId(orders2.getCustomerId());
			map.put("nickName",customer.getNickName());
			SimpleDateFormat simpleDateFormat=new SimpleDateFormat("YYYY/MM/dd HH:MM:SS");
			if (orders2.getDeliveryTime()==null) {
				map.put("deliverTime","");			
			}
			map.put("beginTime",simpleDateFormat.format(orders2.getBeginTime()));
			map.put("remark",orders2.getRemark());
			map.put("status",orders2.getStatus());
			//收货人
			Customer_address customer_address= ordersDao.getAddressByCuAdId(orders2.getCuAdId());
			map.put("ShouHuoName",customer_address.getName());
			map.put("orderPrice",orders2.getOrderPrice());
			map.put("customerPrice",orders2.getCustomerPrice());
			list.add(map);
		}
		return list;		

	}
	//处理中的订单
	public List<Map<String, Object>> getAllGoingOrdersAndIndent(Model model, Integer currentPage, Integer type) {
		List<Map<String,Object>> list=new ArrayList<>();
		if (type==3) {
			//这是顾客订单
			OrdersPage page=new OrdersPage();
			page.setCurrentPage(currentPage);
			List<Orders> orders=ordersDao.getAllGoingOrder(page);
			Integer rows=ordersDao.getRowsOfAllGoingOrder(page);
			page.setRows(rows);
			model.addAttribute("page",page);
			for(Orders orders2:orders){
				Map<String,Object> map=new HashMap<>();
				//订单id ,下单人, 收货人,下单时间,交货时间,备注,订单状态, 订单价格
				map.put("orderId",orders2.getOrderId());
				Customer customer=ordersDao.getCustomerByCustomerId(orders2.getCustomerId());
				map.put("nickName",customer.getNickName());
				SimpleDateFormat simpleDateFormat=new SimpleDateFormat("YYYY/MM/dd HH:MM:SS");
				if (orders2.getDeliveryTime()==null) {
					map.put("deliverTime","");			
				}
				map.put("beginTime",simpleDateFormat.format(orders2.getBeginTime()));
				map.put("remark",orders2.getRemark());
				map.put("status",orders2.getStatus());
				//收货人
				Customer_address customer_address= ordersDao.getAddressByCuAdId(orders2.getCuAdId());
				map.put("ShouHuoName",customer_address.getName());
				map.put("orderPrice",orders2.getOrderPrice());
				map.put("customerPrice",orders2.getCustomerPrice());
				list.add(map);
			}		
		}else{
			//测量,安装 ,维修
			IndentPage indentPage=new IndentPage();
			indentPage.setType(type);
			indentPage.setAfterSale(1);
			indentPage.setCurrentPage(currentPage);
			List<Indent> indents=ordersDao.getAllIndentByIndentPage(indentPage);	
			for(Indent indent:indents){
				//订单id,下单时间, 下单人, 地址联系人,下单地址,定金,客户预约时间,备注
				Map<String,Object> map=new HashMap<>();
				map.put("indentId",indent.getIndentId());
				SimpleDateFormat simpleDateFormat=new SimpleDateFormat("YYYY/MM/dd HH:MM:SS");
				map.put("beginTime",simpleDateFormat.format(indent.getBeginTime()));
				if (indent.getCustomerId()!=null&&indent.getDealerId()==null){
					Customer customer = ordersDao.getCustomerByCustomerId(indent.getCustomerId());
					if (customer.getPhone()==null) {
						map.put("xiaDanRen",customer.getNickName()+"(子账号)");
					}else{
						map.put("xiaDanRen",customer.getNickName()+"(顾客)");
					}
					
				}else if (indent.getCustomerId()==null&&indent.getDealerId()!=null){
					Dealer dealer=ordersDao.getDealerByDealerId(indent.getDealerId());
					map.put("xiadanRen",dealer.getName()+"(经销商)");
				}
				Customer_address address = ordersDao.getAddressByCuAdId(indent.getCuAdId());
				map.put("shouHuoRen",address.getName());
				map.put("address",address.getCity()+address.getAddress());		
				map.put("deposit",indent.getDeposit());
				map.put("subscribeTime",simpleDateFormat.format(indent.getSubscribeTime()));
				map.put("remark",indent.getRemark());
				list.add(map);
			}
		}
		return list;
	}

	//安装测量维修,订单分页
	public IndentPage getPageOfIndentByTypeAndStatus(Integer currentPage,Integer type, Integer status) {
		IndentPage page=new IndentPage();
		page.setType(type);
		page.setCurrentPage(currentPage);
		page.setStatus(status);
		Integer rows=ordersDao.getRowsOfIndentByTypeAndStatus(page);
		page.setRows(rows);
		return page;
	}
	//按页返回所有售后商品信息
	//TODO 逻辑有问题
	public List<Map<String, Object>> getGoodsOfAfterSaleByNew(Model model,Integer currentPage,Integer status) {
		Goods_afterSalesPage goodsPage=new Goods_afterSalesPage();
		goodsPage.setCurrentPage(currentPage);
		goodsPage.setIsHandle(0);
		//得到所有提交的问题的商品
		List<Map<String,Object>> goods=ordersDao.getGoodsOfAfterSale(goodsPage);
		Integer rows=ordersDao.getRowsOfAfterSale(goodsPage);
		goodsPage.setRows(rows);
		model.addAttribute("page",goodsPage);
		//把问题图片提交上去
		SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		List<Map<String,Object>> list=new ArrayList<>();
		for(Map<String,Object> map:goods){
			Integer dis=ordersDao.getDispoiMaxByAfterSalId(map.get("afterSalesId"));
			if (dis==1) {
				List<String> picture=ordersDao.getPictureByAfterSalesId(map.get("afterSalesId"));
				map.put("imgs",picture);
				if (map.get("finishTime")!=null){
					map.put("finishTime",map.get("finishTime"));
				}
				//map.put("disposeTime", simpleDateFormat.format(map.get("disposeTime")));
			}else {
				list.add(map);
			}

		}			
		goods.removeAll(list);
		
		return goods;
	}
	//给新的售后商品进行分页
	public Page getPageOfGoodsOfAfterSale(Integer currentPage) {
		Page page=new Page();
		page.setCurrentPage(currentPage);
		Integer rows=ordersDao.getRowsOfGoodsOfAfterSaleByNew(currentPage);
		page.setRows(rows);
		return page;
	}
	//通过订单号获取所有商品(该商品是指配件)详情
	public List<Map<String, Object>> getGoodsOfAccByOrderId(Integer orderId) {
		List<Map<String,Object>> goods=ordersDao.getGoodOfAccByOrderId(orderId);
		return goods;
	}
	//根据订单号更改订单状态
	public Integer updateOrderStatusByOrderIdAndStatus(Integer orderId, Integer status) {
		Map<String,Object> map=new HashMap<>();
		map.put("orderId", orderId);
		map.put("status", status);
		Integer integer=ordersDao.updateOrderStatusByOrderIdAndStatus(map);
		return integer;
	}
	//根据indent订单号得到所有定的信息
	public Indent getIndentByIndentId(Integer indentId) {
		Indent indent=ordersDao.getIndentByIndentId(indentId);
		return indent;
	}
	//保存增加的费用
	public Integer saveAddMoneyByIdAndMoney(Indent indent) {
		Indent indent2=ordersDao.getIndentByIndentId(indent.getIndentId());
		indent.setAddPrice(indent2.getAddPrice()+indent.getAddPrice());
		Integer integer=ordersDao.updateIndentByIndentIdAndAddPrice(indent);
		return integer;
	}
	//中止或者开启安装测量订单
	public Integer toStopOrStartIndent(Integer indentId, Integer status) {
		Map<String,Object> map=new HashMap<>();
		map.put("indentId",indentId);
		map.put("status",status);
		Integer integer=ordersDao.toStopOrStartIndent(map);
		return integer;
	}
	//根据订单号得到工人的详细信息
	public Map<String,Object> getWorkerByIndentId(Integer indentId) {
		Map<String,Object> worker=ordersDao.getWorkerByIndentId(indentId);
		worker.remove("password");
		return worker;
	}
	//审核订单
	public Integer shenHeDingDan(Integer orderId, Integer status) {
		Map<String,Object> map=new HashMap<>();
		map.put("orderId", orderId);
		map.put("status", status);
		Date date=new Date();
		map.put("shenHeTime",date);
		Integer integer=ordersDao.shenHeDingDan(map);		
		return integer;
	}
	//根据订单号得到该订单的详细信息
	public Map<String, Object> getOrderByOrderId(Integer orderId) {
		Map<String,Object> map=ordersDao.getOrderByOrderId(orderId);
		return map;
	}
	
	public Integer updateSupplyMethod(Integer orderId, String[] goodsIdArray,String[] noGoodsIdArray) {
		//根据商品号修改进货方式 
		if(Integer.parseInt(goodsIdArray[0])!=1){
			Map<String,Object> map=new HashMap<>();
			map.put("goodsId",goodsIdArray[0]);
			map.put("supplyMethod", 1);
			ordersDao.updateGoodsSupplyMethod(map);
		}
		if(Integer.parseInt(noGoodsIdArray[0])!=1){
			Map<String,Object> map=new HashMap<>();
			map.put("goodsId",noGoodsIdArray[0]);
			map.put("supplyMethod", 0);
			ordersDao.updateGoodsSupplyMethod(map);
		}
		Map<String,Object> map=new HashMap<>();
		map.put("orderId", orderId);
		map.put("status",4);
		Date date=new Date();
		map.put("shenHeTime",date);
		ordersDao.shenHeDingDan(map);
		Integer integer = ordersDao.updateOrderStatusByOrderIdAndStatus(map);
		return integer;
	}



}
